import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { get_channel } from '@/api/auth';
import { PcMenuCategory } from '@/common/constants';
import router from '@/router';
import $ from 'dfish-widget';

export default defineStore(
  'router',
  () => {
    const routerList = ref([]);
    const currentChannel = ref(0);
    const channelList = ref([]);
    const menuList = computed(() => channelList.value[currentChannel.value]?.menuList);
    const navMenuList = ref([]);
    const viewsMap = import.meta.glob('@/views/**/*.vue');

    const generateRouter = async () => {
      const res = await get_channel({ menuCategory: PcMenuCategory });
      let result = true;
      if (res?.content?.length) {
        const { content } = res;
        channelList.value = content;
        const menuList = content
          .map((item) => item.menuList)
          .filter((item) => item)
          .flat();
        navMenuList.value = generateNavMenuList();
        routerList.value = menuToRouter(menuList);
        routerList.value.forEach((item) => {
          router.addRoute('layout', item);
        });
      } else {
        result = false;
      }
      return Promise.resolve(result);
    };

    const getchildMenu = (menus) => {
      const resultList = [];
      menus.forEach((item) => {
        if (item.children?.length) {
          resultList.push(...getchildMenu(item.children));
        } else {
          resultList.push(item);
        }
      });
      return resultList;
    };

    const generateNavMenuList = () => {
      const channels = $.cloneDeep(channelList.value);
      channels.forEach((channel) => {
        channel.menuList?.forEach((menu) => {
          if (menu.children?.length) {
            menu.children = getchildMenu(menu.children);
          }
        });
      });
      return channels;
    };

    const menuToRouter = (list) => {
      const resultList = [];
      list.forEach((item) => {
        if (item?.children?.length) {
          resultList.push(...menuToRouter(item.children));
        } else {
          resultList.push({
            path: item.menuAction,
            name: item.menuCode,
            meta: { title: item.menuName, id: item.menuId },
            component: viewsMap[`/src/views/${item.menuRoute}.vue`]
          });
        }
      });
      return resultList;
    };

    const reset = () => {
      menuList.value = [];
      routerList.value.forEach(({ name }) => {
        router.removeRoute(name);
      });
      routerList.value = [];
    };

    return {
      channelList,
      routerList,
      menuList,
      navMenuList,
      currentChannel,
      generateRouter,
      reset
    };
  },
  {
    persist: {
      enabled: true,
      strategies: [{ storage: sessionStorage, paths: ['currentChannel'] }]
    }
  }
);
